<template>
  <div>
    <el-dialog
      class="dia-style"
      :title="title"
      :visible.sync="isOpen"
      width="60%"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <el-form ref="form" :model="formData" :rules="rules" label-width="100px" @submit.native.prevent>
        <el-form-item label="作业名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入作业名称" maxlength="255" />
        </el-form-item>
        <el-form-item label="作业类型" prop="type">
          <el-radio-group v-model="formData.type" @change="handleChange($event, 'type')">
            <el-radio-button label="0">被动采集</el-radio-button>
            <el-radio-button label="1">主动采集</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择任务" prop="importProduct">
          <el-button icon="el-icon-thumb" @click="handleSelectData">请选择</el-button>
          <HkTable
            ref="table"
            :loading="loading"
            :table-data="importProduct"
            :table-columns="tableLabelList"
            :operate="true"
            :show-index="true"
            :is-need-index="true"
            :show-pag="false"
          >
            <template #outputDatasourceName="scope">
              <span v-for="(i, idx) in scope.row.row.outputDatasourceName" :key="idx" style="margin: 0 5px">{{
                i
              }}</span>
            </template>
            <template #gatherMode="scope">
              {{ scope.row.row.gatherMode == 0 ? '主动' : '被动' }}
            </template>
            <template #operate="scope">
              <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </HkTable>
        </el-form-item>
        <el-row v-if="formData.type == '1'">
          <el-col :span="24">
            <el-form-item label="执行方式" prop="cronType">
              <el-radio-group v-model="formData.cronType" @change="handleChange($event, 'cronType')">
                <el-radio label="1">周期性执行</el-radio>
                <el-radio label="2">定期执行</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行配置" prop="PerformConfiguration">
              <div class="son-panel">
                <template v-if="formData.cronType == 1">
                  <span style="margin: 0 5px">每 </span>
                  <el-form-item prop="cycleTime">
                    <el-input-number
                      v-model="formData.cycleTime"
                      style="margin: 0 10px 0 0"
                      controls-position="right"
                      :min="1"
                      :max="60"
                    />
                  </el-form-item>
                  <el-form-item prop="cycleNode">
                    <el-select v-model="formData.cycleNode" placeholder="请选择">
                      <el-option
                        v-for="item in cycleNodeOption"
                        :key="item.itemLabel+item.itemVale"
                        :label="item.itemLabel"
                        :value="item.itemVale"
                      />
                    </el-select>
                  </el-form-item>
                </template>
                <template v-if="formData.cronType == '2'">
                  <el-form-item prop="timeNode">
                    <el-select
                      v-model="formData.timeNode"
                      style="margin: 0 10px 0 0"
                      placeholder="请选择"
                      prop="timeNode"
                    >
                      <el-option
                        v-for="item in timeNodeOptions"
                        :key="item.itemLabel+item.itemVale"
                        :label="item.itemLabel"
                        :value="item.itemVale"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item v-if="formData.timeNode == 'weekly' || formData.timeNode == 'monthly'" prop="day">
                    <el-select
                      v-if="formData.timeNode == 'weekly'"
                      v-model="formData.day"
                      style="margin: 0 10px 0 0"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in cronWeeklyOptions"
                        :key="item.itemLabel+item.itemVale"
                        :label="item.itemLabel"
                        :value="item.itemVale"
                      />
                    </el-select>
                    <el-select
                      v-if="formData.timeNode == 'monthly'"
                      v-model="formData.day"
                      style="margin: 0 10px 0 0"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in monthlyOptions"
                        :key="item.itemLabel+item.itemVale"
                        :label="item.itemLabel"
                        :value="item.itemVale"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item prop="times">
                    <el-select v-model="formData.times" placeholder="请选择">
                      <el-option
                        v-for="item in timesOptions"
                        :key="item.itemLabel+item.itemVale"
                        :label="item.itemLabel"
                        :value="item.itemVale"
                      />
                    </el-select>
                  </el-form-item>
                </template>
                <span style="margin: 0 5px">执行一次</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <SelectDialog
      ref="selectRef"
      title="选择任务"
      :type="formData.type"
      :current-data="importProduct"
      :current-id="currentId"
      @handleSubmit="dialogSubmitEvent"
    />
  </div>
</template>

<script>
import HkTable from '@/components/Hk-Table'
import monthlyOptions from '@/mock/mockData/prodtctType.json'
import SelectDialog from '../components/taskSelector'
import { schedulingSave, getDictList, schedulingUpdate } from '@/api/milkyway/jobScheduling'

export default {
  name: 'EditDialog',
  components: { SelectDialog, HkTable },
  props: {
    title: {
      type: String,
      default() {
        return '编辑'
      }
    },
    echoData: {
      type: Object,
      default() {
        return {}
      }
    },
    tableData: {
      type: Array,
      default() {
        return []
      }
    },
    currentId: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      loading: false,
      tableLabelList: [
        { label: '任务名称', param: 'taskName' },
        { label: '接入数据源', param: 'datasourceName' },
        { label: '输出数据源', param: 'outputDatasourceName', type: 'slot' },
        { label: '采集模式', param: 'gatherMode', type: 'slot' }
      ],
      isOpen: this.open,
      formData: {
        cronType: '1',
        type: '0',
        name: '',
        cycleTime: 0,
        timeNode: '',
        times: '',
        cycleNode: '',
        day: ''
      },
      cycleNodeOption: [],
      timeNodeOptions: [],
      // 每周
      cronWeeklyOptions: [],
      // 每月
      monthlyOptions: monthlyOptions,
      timesOptions: [],
      showAddDialog: false,
      showSelectDialog: false,
      importProduct: [],
      // 表单参数
      rules: {
        name: [{ required: true, message: '作业名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '请选择作业类型', trigger: 'blur' }],
        // cycleTime: [{ required: true, message: '请选择', trigger: 'blur' }],
        timeNode: [{ required: true, message: '请选择', trigger: 'blur' }],
        cycleNode: [{ required: true, message: '请选择', trigger: 'blur' }],
        day: [{ required: true, message: '请选择', trigger: 'blur' }],
        times: [{ required: true, message: '请选择', trigger: 'blur' }],
        monthly: [{ required: true, message: '请选择', trigger: 'blur' }]
      }
    }
  },
  watch: {
    echoData: {
      handler(newValue) {
        if (newValue) {
          this.formData = newValue
        }
      }
    },
    tableData: {
      handler(newVal) {
        this.importProduct = newVal
      }
    }
  },
  mounted() {
    this.getConfigureObj()
  },
  methods: {
    /**  显示弹窗 */
    show() {
      this.reset()
      this.isOpen = true
    },
    reset() {
      this.formData = {
        cronType: '1',
        type: '0',
        name: '',
        cycleTime: 0,
        timeNode: '',
        times: '',
        cycleNode: '',
        day: ''
      }
      this.importProduct = []
    },
    /** 获取执行配置下拉框的数据 */
    getConfigureObj() {
      //   获取周期性执行 分钟/小时
      getDictList('cronCycle').then((res) => {
        this.cycleNodeOption = res
      })
      //   获取定期执行 每天、每月、每周
      getDictList('cronTiming').then((res) => {
        this.timeNodeOptions = res
      })
      //   每周
      getDictList('cronWeekly').then((res) => {
        this.cronWeeklyOptions = res
      })
      //  每小时
      getDictList('cronHour').then((res) => {
        this.timesOptions = res
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      if (this.formData.timeNode == 'day') {
        this.formData.day = '-'
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let cron
          if (this.formData.type == 1) {
            if (this.formData.cronType == '1') {
              cron = `${this.formData.cycleTime}_${this.formData.cycleNode}`
            } else {
              if (this.formData.day && this.formData.day != '-') {
                cron = `${this.formData.timeNode}_${this.formData.day}_${this.formData.times}`
              } else {
                cron = `${this.formData.timeNode}_${this.formData.times}`
              }
            }
          } else {
            this.formData = {
              cronType: this.formData.cronType,
              type: this.formData.type,
              name: this.formData.name,
              cycleTime: 0,
              timeNode: '',
              times: '',
              cycleNode: ''
            }
          }
          if (!this.currentId) {
            schedulingSave({
              scheduling: Object.assign({}, this.formData, { cron: cron }),
              taskDtoList: this.importProduct
            }).then((res) => {
              this.isOpen = false
              this.reset()
              this.$emit('submitForm')
              this.$message.success('保存成功')
            })
          } else {
            this.formData.id = this.currentId
            schedulingUpdate({
              scheduling: Object.assign({}, this.formData, { cron: cron }),
              taskDtoList: this.importProduct,
              id: this.currentId
            }).then((res) => {
              this.isOpen = false
              this.reset()
              this.$emit('submitForm')
              this.$message.success('保存成功')
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.isOpen = false
      this.$refs.form.resetFields()
      this.reset()
    },
    /** 删除按钮操作 */
    handleDelete(data) {
      const name = data.row.taskName
      const _self = this
      this.$modal.confirm('是否确认删除角色编号为"' + name + '"的数据项？').then(function() {
        _self.importProduct.splice(data.index, 1)
      })
    },
    /**  点击 ‘请选择’ **/
    handleSelectData() {
      this.$refs.selectRef.show()
    },
    /**  关闭弹窗 **/
    handleSelectOpen(value) {
      this.showSelectDialog = value
    },
    /** 请选择点击保存后的事件*/
    dialogSubmitEvent(data) {
      this.importProduct = data
    },
    /** 作业类型改变事件 */
    handleChange(value, type) {
      this.formData[type] = value.toString()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-cascader {
  width: 100%;
}

.dialog-footer {
  width: 100% !important;
  display: block !important;
}

.el-form-item__label {
  width: 140px !important;
}

.el-form-item__content {
  margin-left: 140px !important;
}

.son-panel {
  display: flex;
}
</style>
